<?php

namespace app\controller\admin\sky;

use app\model\admin\sky\SkyCandleData;
use laytp\controller\Backend;
use laytp\library\CommonFun;
use think\facade\Db;
use think\response\Json;

/**
 * Class Candle
 * @package app\controller\admin\sky
 */
class CandleData extends Backend
{
    /**
     *
     * @var Candle
     */
    protected $model;
    protected $hasSoftDel = 0;//是否拥有软删除功能

    protected $noNeedLogin = []; // 无需登录即可请求的方法
    protected $noNeedAuth = ['index', 'info']; // 无需鉴权即可请求的方法

    public $orderRule = ['id' => 'desc'];

    public function _initialize()
    {
        $this->model = new SkyCandleData();
    }


    //添加
    public function add()
    {
        try {
            $post = $this->request->post();
            $saveData = [
                'type' => $post['type'],
                'area' => $post['area'],
                'img' => json_encode(explode(',', $post['img']), JSON_UNESCAPED_UNICODE),
            ];
            $saveAll = $this->model->save($saveData);
            if (!$saveAll) throw new \Exception('保存失败');

            $this->clearCache();
            return $this->success('操作成功');
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }


    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit()
    {
        $id = $this->request->param('id');
        $post = CommonFun::filterPostData($this->request->post());
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        $row->type = $post['type'];
        $row->area = $post['area'];
        $row->img = json_encode(explode(',', $post['img']), JSON_UNESCAPED_UNICODE);
        try {
            $save = $row->save();
            if ($save === false) throw new \Exception('保存失败');
            $this->clearCache();
            return $this->success('保存成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }


    public function info()
    {
        $id = $this->request->param('id');
        $candle = $this->model->where('id', $id)->find()->toArray();
        $candle['img'] = json_decode($candle['img'], true);

        return $this->success('获取成功', $candle);
    }


    public function getTreeData()
    {
        $candles = $this->model->order("id desc")->column("id,area as name,type", "id");
        $list = [
            1=>['id' => 1, 'name' => "今日大蜡烛"],
            2=>['id' => 2, 'name' => "季节大蜡烛"],
        ];
        foreach ($candles as $item) {
            $item['name'] = $item['name']."（".$list[$item['type']]['name']."）";
            $list[$item['type']]['children'][] = $item;
        }
        foreach ($list as &$item) {
            $item['id'] = "b" . $item['id'];
        }
        return $this->success("", array_values($list));
    }
}